package com.cloud.school.bus.teacherhelper.modules.home.recorder;

import java.io.File;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Video.Thumbnails;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.support.jhf.debug.DebugLog;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.activity.BaseActivity;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.home.UploadFileStuSelectedActivity;

/**
 * 播放视频 flag 0录制完播放，1单独的播放视频
 * 
 * @author jiahongfei
 * 
 */
public class VideoPlayActivity extends BaseActivity implements
		SurfaceHolder.Callback, OnCompletionListener {
	/** Called when the activity is first created. */
	MediaPlayer player;
	SurfaceView surface;
	SurfaceHolder surfaceHolder;
	// Button play, pause, stop;
	String pathString;
	/** 0录制完播放，1单独的播放视频 */
	private int mFlag = 0;

	private ImageView mPrevirePlayBg;
	private ViewGroup mPreviewImageParent;
	/** 重拍 */
	private Button mPlayCancel;
	private Button mPlayNext;
	private Button mPlaySave;
	private Button mCancelButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_play);

		mFlag = getIntent().getIntExtra("flag", 0);
		pathString = getIntent().getStringExtra("path");

		mPreviewImageParent = (ViewGroup) findViewById(R.id.preview_image_parent);
		mPreviewImageParent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				DebugLog.logI("mPreviewImageParent");
				player.start();
				mPreviewImageParent.setVisibility(View.GONE);
			}
		});
		mPrevirePlayBg = (ImageView) findViewById(R.id.previre_play_bg);
		if (pathString.endsWith("MP4") || pathString.endsWith("mp4")) {
			Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(pathString,
					Thumbnails.MINI_KIND);
			if (null != bitmap) {
				mPrevirePlayBg.setImageBitmap(bitmap);
			}
		}

		mPlayCancel = (Button) findViewById(R.id.play_cancel);
		mPlayCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				retakeVideo();
			}
		});
		mPlayNext = (Button) findViewById(R.id.play_next);
		mPlayNext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				next();
			}
		});
		mPlaySave = (Button) findViewById(R.id.saveButton);
		mPlaySave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				saveVideo();
			}
		});
		mCancelButton = (Button) findViewById(R.id.cancelButton);
		mCancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		if (1 == mFlag) {
			mPlayCancel.setVisibility(View.GONE);
			mPlayNext.setVisibility(View.GONE);
			mPlaySave.setVisibility(View.GONE);
			mCancelButton.setVisibility(View.VISIBLE);
		} else if (0 == mFlag) {
			mCancelButton.setVisibility(View.GONE);
		}

		surface = (SurfaceView) findViewById(R.id.surfaceview);

		surfaceHolder = surface.getHolder();// SurfaceHolder是SurfaceView的控制接口
		surfaceHolder.addCallback(this); // 因为这个类实现了SurfaceHolder.Callback接口，所以回调参数直接this
		// surfaceHolder.setFixedSize(320, 220);//显示的分辨率,不设置为视频默认
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// Surface类型

	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		// 必须在surface创建后才能初始化MediaPlayer,否则不会显示图像
		player = new MediaPlayer();
		player.setOnCompletionListener(this);
		player.setAudioStreamType(AudioManager.STREAM_MUSIC);
		player.setDisplay(surfaceHolder);
		// 设置显示视频显示在SurfaceView上
		try {
			player.setDataSource(pathString);
			player.prepare();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (player.isPlaying()) {
			player.stop();
		}
		player.release();
		// Activity销毁时停止播放，释放资源。不做这个操作，即使退出还是能听到视频播放的声音
	}

	private void stop() {
		player.stop();
	}

	/**
	 * 下一步,进行上传
	 */
	private void next() {
		stop();
		Picture picture = new Picture();
		picture.setPicturePath(pathString);
		Intent intent = new Intent(mContext,
				UploadFileStuSelectedActivity.class);
		intent.putExtra("title", getString(R.string.upload_video));
		intent.putExtra("index", -1);
		intent.putExtra("picture", picture);
		startActivityForResult(intent, 0);
		finish();
	}

	/**
	 * 重拍视频
	 */
	private void retakeVideo() {
		// 暂停播放
		stop();
		// 重拍删除视频和图片
		File videoFile = new File(pathString);
		// File imageFile = new File(imagePath);
		videoFile.delete();
		// imageFile.delete();
		// 销毁自己跳转到视频拍摄界面
		Intent intent = new Intent(this, FFmpegRecorderActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}

	/**
	 * 保存视频
	 */
	private void saveVideo() {
		showSaveVideoDialog();
	}

	private void showSaveVideoDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog
				.setTitleMessage(getString(R.string.tips), Color.BLACK);
		customAlertDialog.setMessage(getString(R.string.save_draft));
		customAlertDialog.setLeftButton(getString(R.string.save),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						stop();
						Intent intent = new Intent(mContext,
								SlidingActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						finish();
					}
				});
		customAlertDialog.setRightButton(getString(R.string.cancel),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {

					}
				});
		customAlertDialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (0 == mFlag) {
				retakeVideo();
			} else if (1 == mFlag) {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		mPreviewImageParent.setVisibility(View.VISIBLE);
		// stop();
	}
}
